package com.yipinhouse.signing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yipinhouse.common.enums.HouseStatusEnum;
import com.yipinhouse.common.enums.HouseTypeEnum;
import com.yipinhouse.common.exception.HouseException;
import com.yipinhouse.common.result.Result;
import com.yipinhouse.employee.client.BrokerInfoQueryClient;
import com.yipinhouse.employee.client.result.BrokerInfoResult;
import com.yipinhouse.house.client.*;
import com.yipinhouse.house.client.result.ResoldApartmentInfoResult;
import com.yipinhouse.house.client.result.ResoldHousingResult;
import com.yipinhouse.signing.common.IntentionMoneyStatusEnum;
import com.yipinhouse.signing.common.SigningResultCode;
import com.yipinhouse.signing.common.enums.ContractTypeEnums;
import com.yipinhouse.signing.common.enums.SellerTypeEnums;
import com.yipinhouse.signing.infra.model.Contract;
import com.yipinhouse.signing.infra.mapper.ContractMapper;
import com.yipinhouse.signing.infra.model.IntentionMoney;
import com.yipinhouse.signing.service.ContractService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yipinhouse.signing.service.IntentionMoneyService;
import com.yipinhouse.signing.service.dto.ContractDto;
import com.yipinhouse.signing.service.param.UploadContractServiceParam;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 合同表 服务实现类
 * </p>
 *
 * @author WangCong
 * @since 2022-12-01
 */
@Service
@Slf4j
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements ContractService {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private NewHouseQueryClient newHouseQueryClient;

    @Resource
    private ResoldApartmentQueryClient resoldApartmentQueryClient;

    @Resource
    private ResoldHouseQueryClient resoldHouseQueryClient;

    @Resource
    private IntentionMoneyService intentionMoneyService;

    @Resource
    private ResoldApartmentManageClient resoldApartmentManageClient;

    @Resource
    private ResoldHouseManageClient resoldHouseManageClient;

    @Resource
    private BrokerInfoQueryClient brokerInfoQueryClient;



    /**
     * 签订房屋合同
     * 分布式锁，锁住房源
     * @param param
     */
    @Override
    @GlobalTransactional
    public void uploadContract(UploadContractServiceParam param) {
        log.info("service:上传合同:参数:{}", param);

//        获取意向表信息
        IntentionMoney intentionMoney = intentionMoneyService.getOne(new QueryWrapper<IntentionMoney>()
                .eq("id", param.getIntentionId())
                .eq("status", IntentionMoneyStatusEnum.PAID));

        if (intentionMoney==null)
            throw new HouseException(SigningResultCode.CONTRACT_NOT_EXISTS);

        String houseType = intentionMoney.getHouseType();
        String newHouse = HouseTypeEnum.NEW_HOUSE.getCode();
        String rent = HouseTypeEnum.RENTAL_HOUSING.getCode();
        String resold = HouseTypeEnum.SECOND_HAND_HOUSING.getCode();

//        查询房源状态是否为已预定
        Result houseStatusResult = null;
        if (houseType.equals(newHouse))
            houseStatusResult = newHouseQueryClient.checkHouseStatus(intentionMoney.getHouseId());

        else if (houseType.equals(resold))
            houseStatusResult = resoldApartmentQueryClient.checkHouseStatus(intentionMoney.getHouseId());

        else if (houseType.equals(rent))
            houseStatusResult = resoldHouseQueryClient.checkHouseStatus(intentionMoney.getHouseId());

        if (houseStatusResult == null || (!houseStatusResult.isSuccess()))
            throw new HouseException("分表查询错误", 600);

        String houseStatus = String.valueOf(houseStatusResult.getData());

        if (!houseStatus.equals(HouseStatusEnum.ORDERED.getCode()))
            throw new HouseException(SigningResultCode.HOUSE_NOT_ORDERED);

//        房源已被预定，查询房源的预定人是谁
        IntentionMoney intention = intentionMoneyService.getOne(new QueryWrapper<IntentionMoney>()
                .eq("broker_id", intentionMoney.getBrokerId())
                .eq("user_id", intentionMoney.getUserId())
                .eq("house_id", intentionMoney.getHouseId())
                        .eq("house_type",houseType)
                .eq("status", IntentionMoneyStatusEnum.PAID.getCode()));

        if (intention==null)
            throw new HouseException(SigningResultCode.HOUSE_ORDERED);

//        获取门店id
        BrokerInfoResult brokerInfo = brokerInfoQueryClient.getBrokerInfo(intention.getBrokerId()).getData();
        Integer shopId = brokerInfo.getShopId();


//        创建合同对象
        Contract contract = new Contract();

//        设置合同编号
        contract.setContractNo("ht"+ IdUtil.getSnowflake().nextIdStr());

        //设置合同的类型，是租赁，还是出售
        if (houseType.equals(rent))
            contract.setContractType(ContractTypeEnums.LEASE.getCode());
        else
            contract.setContractType(ContractTypeEnums.BUY.getCode());

        //        设置用户id
        contract.setUserId(intention.getUserId());

//        设置意向金id
        contract.setIntentionId(intention.getId());

//        设置经纪人id
        contract.setBrokerId(intention.getBrokerId());


//        设置出售人id
        Integer ownerId = null;
        if (houseType.equals(newHouse))
            contract.setSellerId(shopId);
        else {
            if (houseType.equals(resold)) {
                Result<ResoldApartmentInfoResult> result = resoldApartmentQueryClient.getResoldApartmentInfo(intention.getHouseId());
                ownerId = result.getData().getUserId();
            }else if (houseType.equals(rent)){
                System.out.println("这个值============"+intention.getHouseId()+"=========");
                Result<ResoldHousingResult> result = resoldHouseQueryClient.getResoldHouseInfo(intention.getHouseId());
                ownerId = result.getData().getUserId();
            }
            contract.setSellerId(ownerId);

        }


//        设置合同出售人（乙方）是门店，还是业主
        if (houseType.equals(rent)||houseType.equals(resold))
            contract.setSellerType(SellerTypeEnums.USER.getCode());
        else
            contract.setSellerType(SellerTypeEnums.SHOP.getCode());

//        设置房源id
        contract.setHouseId(intention.getHouseId());

//        设置房源类型
        contract.setHouseType(intention.getHouseType());


        //设置房源的中文
        //TODO 统一房源的字段
        if (houseType.equals(newHouse))
            contract.setHouseTypeValue(HouseTypeEnum.NEW_HOUSE.getMessage());
        else if (houseType.equals(rent))
            contract.setHouseTypeValue(HouseTypeEnum.RENTAL_HOUSING.getMessage());
        else if (houseType.equals(resold))
            contract.setHouseTypeValue(HouseTypeEnum.SECOND_HAND_HOUSING.getMessage());
        contract.setTime(DateUtil.now());

//        设置成交价
        contract.setTradePrice(param.getTradePrice());

        //设置首付款
        contract.setDownPayment(param.getDownPayment());

        this.save(contract);
    }

    @Override
    public List<ContractDto> getContractByUser(Integer userId) {
        List<Contract> contracts = this.list(new QueryWrapper<Contract>()
                .eq("user_id",userId));

        if (contracts==null)
            return null;

        List<ContractDto> dtos = BeanUtil.copyToList(contracts, ContractDto.class);
        return dtos;
    }
}
